package com.duan.nowcoder.community.controller;

import com.duan.nowcoder.community.entity.DiscussPost;
import com.duan.nowcoder.community.service.DiscussPostService;
import com.duan.nowcoder.community.entity.Page;
import com.duan.nowcoder.community.service.LikeService;
import com.duan.nowcoder.community.service.MessageService;
import com.duan.nowcoder.community.service.UserService;
import com.duan.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;


    @GetMapping("/index")
    public String getIndexPage(Model model, Page page, @RequestParam(name = "sortMode", defaultValue = "1") int sortMode) {
        /*方法调用前，springMVC会自动实例化model和page，并将page注入model
        所以thymelaf中可以直接访问page对象中的数据
        */
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/index?sortMode=" + sortMode);
        List<DiscussPost> list = discussPostService.selectDiscussPost(0, page.getOffset(), page.getLimit(), sortMode);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                map.put("user", userService.findUserById(post.getUserId()));
                Long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("sortMode", sortMode);
        return "index";
    }
}
